<template>
  <el-cascader
    class="select-company"
    v-model="baseParamStore.baseParam.orgId"
    :options="options"
    placeholder="请选择"
    @change="handleChange"
    ref="refCascader"
  />
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { SbLeftTreeByEntity } from '@/api/api'
import { useBaseParamStore } from '@/stores/baseParams'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 配置获取猪群信息存储
const baseParamStore = useBaseParamStore()

const selectedValue = ref([])

const options = ref()
const refCascader = ref()

const handleChange = (value) => {
  selectedValue.value = value[value.length - 1]
  baseParamStore.baseParam.orgId = selectedValue.value
  // 构造新的查询参数对象
  const newQuery = {
    ...route.query,
    orgId: selectedValue.value, // 替换或新增 orgId 参数
    orgName: refCascader.value.getCheckedNodes()[0].label
  }

  // 使用 router.replace 更新地址栏，不触发页面刷新
  router.replace({
    path: route.path,
    query: newQuery
  })
  setTimeout(() => {
    location.reload()
  }, 100)
}

const transformChildren = (nodes, level = 1) => {
  if (level >= 5) return undefined // 超过 5 层不返回 children

  return nodes.map((node) => ({
    value: node.id,
    label: node.text,
    children: node.children ? transformChildren(node.children, level + 1) : undefined
  }))
}

// 获取组织树
const fetchSbLeftTreeByEntity = async () => {
  try {
    const res = await SbLeftTreeByEntity({
      entityId: 'wens_patrol_alarm',
      orgField: 'wens_org'
    })
    if (res && res.data) {
      options.value = res.data.map((item) => {
        return {
          value: item.id,
          label: item.text,
          children: item.children ? transformChildren(item.children) : undefined
        }
      })
    }
  } catch (error) {
    console.error('获取获取告警详情信息失败:', error)
  }
}

onMounted(() => {
  baseParamStore.baseParam.orgId = route.query.orgId
  fetchSbLeftTreeByEntity()
})
</script>
<style>
.select-company {
  width: 300px;
}
/deep/ .el-tag.el-tag--info {
  background-color: #123493;
  border-color: rgba(57, 106, 254, 1);
  color: #ffffff;
}
/deep/ .el-cascader__tags .el-tag:not(.is-hit) {
  border-color: rgba(57, 106, 254, 1);
}
</style>
